/*
 *  Copyright (c) 2009 Baturu.COM
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.baturu.oss.dao.jpa;

import com.baturu.oss.dao.OpenCategoryDAO;
import com.baturu.oss.entities.categories.OpenCategory;
import org.sitevelocity.exceptions.NoSuchEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author javafuns
 */
public class OpenCategoryDAOImpl implements OpenCategoryDAO {

    private PersistenceManager pm;

    public OpenCategoryDAOImpl(PersistenceManager pm) {
        this.pm = pm;
    }

    @Override
    public OpenCategory newCategory(OpenCategory category) {
        return this.pm.makePersistent(category);
    }

    @Override
    public List<OpenCategory> findCategories(int maxResults, int firstResult, String orderByDesc) {
        Query query = pm.newQuery("select from " + OpenCategory.class.getName());
        if (maxResults >= 0) {
            if (firstResult < 0) {
                firstResult = 0;
            }
            query.setRange(firstResult, firstResult + maxResults);
        }
        if (orderByDesc == null || "".equals(orderByDesc)) {
            orderByDesc = "id asc";
        }
        query.setOrdering(orderByDesc);
        List<OpenCategory> ols = (List<OpenCategory>) query.execute();
        return (ols==null?new ArrayList<OpenCategory>(0):ols);
    }

    @Override
    public void removeCategory(String id) {
        this.pm.deletePersistent(this.getCategory(id));
    }

    @Override
    public void updateCategory(OpenCategory cat) throws NoSuchEntityException {
        if (this.getCategory(cat.getId()) == null) {
            throw new NoSuchEntityException("The openLink with id " + cat.getId() + " no longer exists.");
        }
        this.pm.makePersistent(cat);
    }

    @Override
    public OpenCategory getCategory(String id) {
        return this.pm.getObjectById(OpenCategory.class, id);
    }

    @Override
    public int getCategoryCount() {
        String querySQL = "select count(id) from " + OpenCategory.class.getName();
        Query query = this.pm.newQuery(querySQL);
        Number count = (Number) query.execute();
        return count.intValue();
    }
}
